package com.yss.system.service.impl;

import java.util.Comparator;
import java.util.Date;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;
import javax.annotation.PostConstruct;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.conditions.update.UpdateWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.yss.common.core.enums.YssStatusEnum;
import com.yss.common.core.utils.uuid.IdUtils;
import com.yss.common.security.utils.SecurityUtils;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import com.yss.common.core.constant.UserConstants;
import com.yss.common.core.exception.BusinessException;
import com.yss.common.core.utils.StringUtils;
import com.yss.common.security.utils.DictUtils;
import com.yss.system.api.domain.SysDictData;
import com.yss.system.api.domain.SysDictType;
import com.yss.system.mapper.SysDictDataMapper;
import com.yss.system.mapper.SysDictTypeMapper;
import com.yss.system.service.ISysDictTypeService;
import org.springframework.util.CollectionUtils;

/**
 * 字典 业务层处理
 */
@Slf4j
@Service
public class SysDictTypeServiceImpl extends ServiceImpl<SysDictTypeMapper, SysDictType> implements ISysDictTypeService {
    @Autowired
    private SysDictTypeMapper dictTypeMapper;

    @Autowired
    private SysDictDataMapper dictDataMapper;

    /**
     * 项目启动时，初始化字典到缓存
     */
    @PostConstruct
    public void init() {
        loadingDictCache();
    }

    /**
     * 根据条件分页查询字典类型
     *
     * @param dictType 字典类型信息
     * @return 字典类型集合信息
     */
    @Override
    public List<SysDictType> selectDictTypeList(SysDictType dictType) {
        QueryWrapper<SysDictType> wrapper = new QueryWrapper<>();
        wrapper.orderByDesc("STATUS" );
        wrapper.orderByDesc("CREATE_TIME" );
        if (null == dictType) {
            return this.list(wrapper);
        }
        if (StringUtils.isNotEmpty(dictType.getDictName())) {
            wrapper.like("DICT_NAME" , dictType.getDictName());
        }
        if (null != dictType.getStatus()) {
            wrapper.like("STATUS" , dictType.getStatus());
        }
        if (StringUtils.isNotEmpty(dictType.getDictType())) {
            wrapper.like("DICT_TYPE" , dictType.getDictType());
        }
        if (StringUtils.isNotEmpty(dictType.getParams())) {
            if (null != dictType.getParams().get("beginTime" ) && StringUtils.isNotEmpty(dictType.getParams().get("beginTime" ).toString())) {
                wrapper.ge("CREATE_TIME" , dictType.getParams().get("beginTime" ));
            }
            if (null != dictType.getParams().get("endTime" ) && StringUtils.isNotEmpty(dictType.getParams().get("endTime" ).toString())) {
                wrapper.le("CREATE_TIME" , dictType.getParams().get("endTime" ));
            }
        }
        return this.list(wrapper);
    }

    /**
     * 根据所有字典类型
     *
     * @return 字典类型集合信息
     */
    @Override
    public List<SysDictType> selectDictTypeAll() {
        return this.list();
    }

    /**
     * 根据字典类型查询字典数据
     *
     * @param dictType 字典类型
     * @return 字典数据集合信息
     */
    @Override
    public List<SysDictData> selectDictDataByType(String dictType) {
        List<SysDictData> dictDatas = DictUtils.getDictCache(dictType);
        if (StringUtils.isNotEmpty(dictDatas)) {
            return dictDatas;
        }
        QueryWrapper<SysDictData> wrapper = new QueryWrapper<>();
        wrapper.eq("DICT_TYPE" , dictType);
        dictDatas = dictDataMapper.selectList(wrapper);
        if (StringUtils.isNotEmpty(dictDatas)) {
            DictUtils.setDictCache(dictType, dictDatas);
            return dictDatas;
        }
        return null;
    }

    /**
     * 根据字典类型查询信息
     *
     * @param dictType 字典类型
     * @return 字典类型
     */
    @Override
    public SysDictType selectDictTypeByType(String dictType) {
        QueryWrapper<SysDictType> wrapper = new QueryWrapper<>();
        wrapper.eq("DICT_TYPE" , dictType);
        return this.getOne(wrapper);
    }

    /**
     * 批量删除字典类型信息
     *
     * @param ids 需要删除的字典ID
     */
    @Override
    public void deleteDictTypeByIds(String[] ids) {
        for (String id : ids) {
            SysDictType dictType = this.getById(id);
            QueryWrapper<SysDictData> wrapper = new QueryWrapper<>();
            wrapper.eq("DICT_TYPE" , dictType.getDictType());
            if (dictDataMapper.selectCount(wrapper) > 0) {
                throw new BusinessException(String.format("%1$s已分配,不能删除" , dictType.getDictName()));
            }
            this.removeById(id);
            DictUtils.removeDictCache(dictType.getDictType());
        }
    }

    /**
     * 加载字典缓存数据
     */
    @Override
    public void loadingDictCache() {
        QueryWrapper<SysDictData> wrapper = new QueryWrapper<>();
        wrapper.eq("STATUS" , YssStatusEnum.NORMAL.getCode());
        List<SysDictData> list = dictDataMapper.selectList(wrapper);
        if (CollectionUtils.isEmpty(list)) {
            log.info("没有获取到正常状态的字典信息！" );
            return;
        }
        Map<String, List<SysDictData>> dictDataMap = list.stream().collect(Collectors.groupingBy(SysDictData::getDictType));
        for (Map.Entry<String, List<SysDictData>> entry : dictDataMap.entrySet()) {
            DictUtils.setDictCache(entry.getKey(), entry.getValue().stream().sorted(Comparator.comparing(SysDictData::getOrderNum)).collect(Collectors.toList()));
        }
    }

    /**
     * 清空字典缓存数据
     */
    @Override
    public void clearDictCache() {
        DictUtils.clearDictCache();
    }

    /**
     * 重置字典缓存数据
     */
    @Override
    public void resetDictCache() {
        clearDictCache();
        loadingDictCache();
    }

    /**
     * 新增保存字典类型信息
     *
     * @param dict 字典类型信息
     * @return 结果
     */
    @Override
    public int insertDictType(SysDictType dict) {
        dict.setId(IdUtils.fastSimpleUUID());
        dict.setCreateBy(SecurityUtils.getUsername());
        dict.setCreateTime(new Date());
        int row = dictTypeMapper.insert(dict);
        if (row > 0) {
            DictUtils.setDictCache(dict.getDictType(), null);
        }
        return row;
    }

    /**
     * 修改保存字典类型信息
     *
     * @param dict 字典类型信息
     * @return 结果
     */
    @Override
    @Transactional
    public int updateDictType(SysDictType dict) {
        SysDictType oldDict = this.getById(dict.getId());
        UpdateWrapper<SysDictData> updateWrapper = new UpdateWrapper<>();
        updateWrapper.eq("DICT_TYPE" , oldDict.getDictType());
        SysDictData sysDictData = new SysDictData();
        sysDictData.setDictType(dict.getDictType());
        dictDataMapper.update(sysDictData, updateWrapper);
        dict.setUpdateBy(SecurityUtils.getUsername());
        dict.setUpdateTime(new Date());
        int row = dictTypeMapper.updateById(dict);
        if (row > 0) {
            QueryWrapper<SysDictData> wrapper = new QueryWrapper<>();
            wrapper.eq("DICT_TYPE" , dict.getDictType());
            List<SysDictData> dictDatas = dictDataMapper.selectList(wrapper);
            DictUtils.setDictCache(dict.getDictType(), dictDatas);
        }
        return row;
    }

    /**
     * 校验字典类型称是否唯一
     *
     * @param dict 字典类型
     * @return 结果
     */
    @Override
    public boolean checkDictTypeUnique(SysDictType dict) {
        String id = StringUtils.isNull(dict.getId()) ? "-1" : dict.getId();
        QueryWrapper<SysDictType> wrapper = new QueryWrapper<>();
        wrapper.eq("DICT_TYPE" , dict.getDictType());
        SysDictType dictType = dictTypeMapper.selectOne(wrapper);
        if (StringUtils.isNotNull(dictType) && !dictType.getId().equals(id)) {
            return UserConstants.NOT_UNIQUE;
        }
        return UserConstants.UNIQUE;
    }
}
